package cn.schoolwow.quickdao.test.module.business.user.dml.userRole.flow.add;

import cn.schoolwow.quickdao.domain.DAO;
import cn.schoolwow.quickdao.test.entity.Role;
import cn.schoolwow.quickdao.test.entity.User;
import cn.schoolwow.quickdao.test.entity.UserRole;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import com.alibaba.fastjson.JSONObject;
import org.junit.Assert;

public class AddUserRoleFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        insertUser(flowContext);
        insertRole(flowContext);
        insertUserRole(flowContext);
    }

    @Override
    public String name() {
        return "插入用户角色表";
    }

    private void insertUser(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);

        User user = new User();
        user.setUsername("管理员");
        user.setPassword("123456");
        user.setEmail("admin@fake.com");
        JSONObject extra = new JSONObject();
        extra.put("age", 10);
        user.setExtraData(extra);
        int effect = dao.insert(user);
        Assert.assertEquals(1, effect);

        flowContext.putTemporaryData("insertUser", user);
    }

    private void insertRole(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);

        Role role = new Role();
        role.setRoleKey("admin");
        role.setRoleName("管理员");
        role.setStatus(1);
        int effect = dao.insert(role);
        Assert.assertEquals(1, effect);

        flowContext.putTemporaryData("insertRole", role);
    }

    private void insertUserRole(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);
        User insertUser = (User) flowContext.checkData("insertUser");
        Role insertRole = (Role) flowContext.checkData("insertRole");

        UserRole userRole = new UserRole();
        userRole.setUserId(insertUser.getId());
        userRole.setRoleId(insertRole.getId());
        int effect = dao.insert(userRole);
        Assert.assertEquals(1, effect);
    }
}
